export default {
    namespaced: true,
    state: {
      items: []
    },
    mutations: {
      ADD_ITEM(state, product) {
        const existingItem = state.items.find(item => item.id === product.id)
        if (existingItem) {
          existingItem.quantity++
        } else {
          state.items.push({ ...product, quantity: 1 })
        }
      },
      REMOVE_ITEM(state, itemId) {
        state.items = state.items.filter(item => item.id !== itemId)
      },
      INCREMENT_ITEM(state, itemId) {
        const item = state.items.find(item => item.id === itemId)
        if (item) item.quantity++
      },
      DECREMENT_ITEM(state, itemId) {
        const item = state.items.find(item => item.id === itemId)
        if (item && item.quantity > 1) {
          item.quantity--
        } else {
          state.items = state.items.filter(item => item.id !== itemId)
        }
      }
    },
    actions: {
      addToCart({ commit }, product) {
        commit('ADD_ITEM', product)
      },
      removeFromCart({ commit }, itemId) {
        commit('REMOVE_ITEM', itemId)
      },
      incrementQuantity({ commit }, itemId) {
        commit('INCREMENT_ITEM', itemId)
      },
      decrementQuantity({ commit }, itemId) {
        commit('DECREMENT_ITEM', itemId)
      }
    },
    getters: {
      cartItems: state => state.items,
      cartTotal: state => {
        return state.items.reduce((total, item) => {
          return total + (item.price * item.quantity)
        }, 0)
      }
    }
  }